//@token_required  # 需要 token 验证
// API基础URL配置
const API_BASE_URL = 'http://localhost:5004';

// 清空内容的函数 ”清空内容“
    function clearContent() {
      // 获取文本框元素
      const contentTextarea = document.getElementById('content');

      // 清空文本框内容
      contentTextarea.value = '';
    }

// 检查并更新用户登录状态
async function updateUserLoginStatus() {
    const userInfoDiv = document.querySelector('.user-info');
    const authButtons = document.querySelector('.auth-buttons');
    const usernameDisplay = document.getElementById('username-display');
    const userInfo = localStorage.getItem('user');
//    console.log(userInfo);// 获取最新的用户信息
    const userProfile = await fetchUserProfile();
//    console.log(userProfile);
    if (userProfile) {
        userInfoDiv.style.display = 'block';
        authButtons.style.display = 'none';
        usernameDisplay.textContent = userProfile.username;
    } else {
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';

    }
}

// 获取用户信息的函数
async function fetchUserProfile() {
    try {
        const token = localStorage.getItem('token');
        if (!token) return null;

        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        if (data.code === 200) {
            return data.data;
        } else {
            console.error('获取用户信息失败:', data.message);
            alert('用户未登录，请先登录！');
            return null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        alert('用户未登录，请先登录！');

        return null;
    }
}

// 退出登录处理函数
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');

        const modal = document.getElementById('user-modal');
        if (modal) {
            modal.style.display = 'none';
        }

        showMessage('已成功退出登录');

        // 更新界面显示
        const userInfoDiv = document.querySelector('.user-info');
        const authButtons = document.querySelector('.auth-buttons');

        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';

        window.location.href = 'index.html';
    }
}

// 消息提示函数
function showMessage(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-toast';
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);

    setTimeout(() => messageDiv.classList.add('show'), 10);

    setTimeout(() => {
        messageDiv.classList.remove('show');
        setTimeout(() => messageDiv.remove(), 300);
    }, 3000);
}

document.addEventListener("DOMContentLoaded", () => {
  // 文件上传按钮事件
  const uploadBtn = document.getElementById("uploadBtn");
  const fileInput = document.getElementById("fileInput");

  uploadBtn.addEventListener("click", () => {
    fileInput.click();
  });

  // 文件选择处理
  fileInput.addEventListener("change", async (event) => {
    const file = event.target.files[0];
    if (!file) return;

//    document.getElementById("fileName").textContent = file.name;
    const fileType = file.name.split('.').pop().toLowerCase();

    try {
      let content = "";

      // 处理TXT文件
      if (fileType === "txt") {
        content = await file.text();
      }
      // 处理PDF/JPG/JPEG/PNG文件
      else if (["pdf", "jpg", "png","jpeg"].includes(fileType)) {
//
 // 1. 创建 FormData 对象
    const formData = new FormData();

    // 2. 获取标题
    const title = document.getElementById('title').value;

    // 3. 添加文件到 FormData
    formData.append("file", file);  // "file" 是接口要求的参数名

    // 4. 添加标题到 FormData
    formData.append("title", title);  // "title" 是接口要求的参数名

    console.log("上传文件:", file.name);
    console.log("作文标题:", title);


        // 5. 发送请求
        const response = await fetch("http://localhost:5004/essay/submit/file", {
            method: "POST",
            headers: {
                "Authorization": `Bearer ${localStorage.getItem("token")}`
                // 注意：不要手动设置 Content-Type，浏览器会自动设置 multipart/form-data 并带上 boundary
            },
            body: formData  // 直接使用 FormData 对象作为 body
        });

        // 6. 处理响应
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        if (result.code === 200) {
        console.log(result);
          content = result.data.recognized_text;
        } else {

          throw new Error(result.message || "文件解析失败");
        }
      } else {
        throw new Error("不支持的文件类型");
      }

      // 填充内容到文本框
      document.getElementById("content").value = content;

    } catch (error) {
      console.error("文件处理失败:", error);
      alert(`文件处理失败: ${error.message}`);
      fileInput.value = "";
      document.getElementById("fileName").textContent = "未选择文件";
    }
  });
});

// 模型映射关系
const modelMap = {
  standard: [{ id: 'gpt', name: 'GPT标准模型' }],
  en: [
    { id: 'gaokao', name: '高考评分模型' },
    { id: 'postgrad', name: '考研评分模型' },
    { id: 'cet', name: '四六级评分模型' }
  ],
  cn: [{ id: 'gaokao', name: '高考评分模型' }],
  fr: [
    { id: 'dalf', name: 'DALF评分模型' },
    { id: 'delf', name: 'DELF评分模型' }
  ],
  ru: [
    { id: 'crt4', name: 'CRT-4（ТРКИ-1 / B1级）评分模型' },
    { id: 'crt6', name: 'CRT-6CRT-6（ТРКИ-2 / B2级）评分模型' }
  ],
  es: [{ id: 'dele', name: 'DELE评分模型' }],
  jp: [
    { id: 'cjt4', name: 'CJT-4评分模型' },
    { id: 'cjt6', name: 'CJT-6评分模型' }
  ]
};

// 当前选中的作文类型
let currentEssayType = 'standard';

// 切换下拉框显示状态
function toggleDropdown(dropdownId) {
  const dropdown = document.getElementById(dropdownId);
  const isHidden = dropdown.classList.contains('hidden');

  // 关闭所有下拉框
  document.querySelectorAll('.dropdown').forEach(d => {
    if (d.id !== dropdownId) d.classList.add('hidden');
  });

  // 切换当前下拉框
  dropdown.classList.toggle('hidden', !isHidden);
}

// 选择作文类型
function selectEssayType(type, displayName) {
  currentEssayType = type;
  document.getElementById('selectedEssayType').innerHTML = `
    <span class="flag-icon ${type} mr-2"></span>
    ${displayName}
  `;
  document.getElementById('typeDropdown').classList.add('hidden');

  // 更新模型选择下拉框
  updateModelDropdown(type);

}

// 更新模型选择下拉框
function updateModelDropdown(essayType) {
  const models = modelMap[essayType] || [];
  const modelDropdown = document.getElementById('modelDropdown');

  // 清空现有选项
  modelDropdown.innerHTML = '';

  // 添加新选项
  models.forEach(model => {
    const option = document.createElement('div');
    option.className = 'px-4 py-2 hover:bg-gray-50 cursor-pointer';
    option.textContent = model.name;
    option.onclick = () => {
      document.getElementById('selectedModel').textContent = model.name;
      modelDropdown.classList.add('hidden');
    };
    modelDropdown.appendChild(option);
  });

  // 默认选择第一个模型
  if (models.length > 0) {
    document.getElementById('selectedModel').textContent = models[0].name;
  }
}

// 点击页面其他位置关闭下拉框
document.addEventListener('click', function(event) {
  if (!event.target.closest('.relative')) {
    document.querySelectorAll('.dropdown').forEach(d => {
      d.classList.add('hidden');
    });
  }
});

// 初始化模型下拉框
document.addEventListener('DOMContentLoaded', () => {
  updateModelDropdown(currentEssayType);
});

// 获取表单数据
function getFormData() {
  return {
    title: document.getElementById('essayTitle').value,
    essayType: currentEssayType,
    feedbackLanguage: document.getElementById('feedbackLanguage').value,
    model: document.getElementById('selectedModel').textContent
  };
}
// 页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    // 更新用户登录状态
    updateUserLoginStatus();

    // 设置用户详情模态窗口事件
    const usernameDisplay = document.getElementById('username-display');
    if (usernameDisplay) {
        usernameDisplay.onclick = async function() {
            const userProfile = await fetchUserProfile();
            if (userProfile) {
                const userModal = document.getElementById('user-modal');
                document.getElementById('modal-username').textContent = userProfile.username;
                document.getElementById('modal-email').textContent = userProfile.email;
                document.getElementById('modal-userid').textContent = userProfile.user_id;
                userModal.style.display = 'block';
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = 'auth.html#login';
            }
        }
    }

    // 设置模态窗口关闭事件
    const closeButton = document.querySelector('.close-button');
    if (closeButton) {
        closeButton.onclick = function() {
            document.getElementById('user-modal').style.display = 'none';
        }
    }

    // 点击模态窗口外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('user-modal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
});


// “开始评分”按钮 提交作文的函数
    async function submitEssay() {
      // 获取作文标题和内容
      const title = document.getElementById('essayTitle').value;
      const text = document.getElementById('content').value;
//        console.log(title,text);
      // 校验标题和内容是否为空
      if (!title || !text) {
        alert('请填写作文标题和内容！');
        return;
      }
        const userProfile = await fetchUserProfile();
        console.log(userProfile);
        if (!userProfile) {
        alert('用户未登录，请先登录！');
        return;
      }
       // 显示评分进度
    const progress = showScoringProgress();
      // 获取用户ID（假设从 localStorage 中获取）
      const user_id = userProfile.user_id;
//     const user_id = document.querySelector('.user-info/user_id');
//      console.log(user_id);

progress.update("正在提交作文...", 20);
      // 发送请求到后端
      const submitResponse = await fetch('http://127.0.0.1:5004/essay/submit/text', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}` // 携带 token
        },
        body: JSON.stringify({
//          user_id: user_id,
          title: title,
          text: text
        })
      })
      progress.update("正在处理提交结果...", 40);
      const submitData = await submitResponse.json();
    if (submitData.code !== 200) {
      throw new Error('作文提交失败: ' + (submitData.message || '未知错误'));
    }


console.log('作文提交成功:', submitData.data);
const essayId = submitData.data.essay_id;
const versionId = submitData.data.version_id;
const safeEssayId = String(essayId);
const  safeVersionId2 = String(versionId);
const safeVersionId = parseInt(versionId, 10);
// 正确的类型检查方式
console.log('作文ID:', safeEssayId, typeof safeEssayId);
console.log('版本ID:', safeVersionId, typeof safeVersionId);

const analysisRequestBody = {
            "essay_id": String(submitData.data.essay_id),  // 必须字符串
            "version_id": parseInt(submitData.data.version_id, 10), // 必须数字
            "essay_knowledge": document.getElementById('selectedEssayType').textContent.replace(/\s+/g, '').replace(/作文$/, ''),  // 固定值（注意图片中的拼写错误）
            "knowledge": document.getElementById('feedbackLanguage').value,
            "modelName": document.getElementById('selectedModel').textContent
        };

        console.log('请求体校验:', JSON.stringify(analysisRequestBody, null, 2));

 progress.update("开始分析作文...", 60);
        // 5. 调用新版分析接口
        const analysisRes = await fetch(`http://127.0.0.1:5004/analysis/essay`,
//            `http://127.0.0.1:5004/analysis/essay/${analysisRequestBody.essay_id}/${analysisRequestBody.version_id}`,
            {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
             body: JSON.stringify({ "essay_id": String(submitData.data.essay_id),  // 必须字符串
            "version_id": parseInt(submitData.data.version_id, 10), // 必须数字
            "essay_knowledge": document.getElementById('selectedEssayType').textContent.replace(/\s+/g, '').replace(/作文$/, ''),  // 固定值（注意图片中的拼写错误）
            "knowledge": document.getElementById('feedbackLanguage').value,
            "modelName": document.getElementById('selectedModel').textContent })
}        );
progress.update("正在生成评分结果...", 80);
        const analysisData = await analysisRes.json();
console.log(analysisData);
        if (analysisData.code !== 200) {
            throw new Error(analysisData.message || '分析失败');
        }

        // 6. 处理结果
        console.log('分析结果:', analysisData.data);
        console.log("传入数据格式",analysisData.data.analysis);
        updateScoreDisplay(analysisData.data.analysis);
   progress.update("评分完成！", 100);
        progress.complete();
//        console.log(String(submitData.data.essay_id), String(submitData.data.version_id));
//fetchEssayAnalysis(String(submitData.data.essay_id), String(submitData.data.version_id))

//

////         **Step 3: 评分后处理**
//        const postProcessRes = await fetch('http://127.0.0.1:5003/model/postprocess', {
//            method: 'POST',
//            headers: {
//                'Content-Type': 'application/json',
//                'Authorization': `Bearer ${localStorage.getItem('token')}`
//            },
////            body: JSON.stringify({ scoreData: scoreData.data || scoreData2.data })
//                body: JSON.stringify({ scoreData: scoreData.data })
//        });
//
//        const postProcessData = await postProcessRes.json();
//        if (postProcessData.code !== 200) {
//            throw new Error('评分后处理失败: ' + postProcessData.message);
//        }
//        console.log('✅ 评分后处理完成:', postProcessData.comments);

// **Step 4: 更新雷达图**
const RadarChart = [{
            essay_id: safeEssayId,
            version_id: safeVersionId2,
        }];
        console.log(RadarChart);
//        updateRadarChart(RadarChart);
updateRadarChart(safeEssayId,safeVersionId2);
// 当前页面 - 点击按钮时跳转并传参
document.getElementById('detailButton').addEventListener('click', () => {

  const data = {
    user_id:user_id,
    essay_id: safeEssayId,
    version_id: safeVersionId2,
  };

  // 将数据转为URL参数
  const params = new URLSearchParams(data).toString();

  // 跳转到目标页并传参
  window.location.href = `data-analysis.html?${params}`;
});

  }

/**
 * 获取作文分析数据
 * @param {string} essayId - 作文ID
 * @param {string} versionId - 版本ID
 * @returns {Promise<Object|null>} 返回分析数据或null
 */
async function fetchEssayAnalysis(essayId, versionId) {
  try {
    // 1. 获取本地存储的token
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('用户未登录，请先登录');
    }

    // 2. 调用现有接口（注意路径参数格式）
    const response = await fetch(`http://127.0.0.1:5004/essay/analysis/${essayId}/${versionId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    });

    // 3. 处理响应
    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      throw new Error(error.message || `请求失败: HTTP ${response.status}`);
    }

    // 4. 解析数据
    const result = await response.json();
    console.log("✅ 评分数据:", result);
    // 5. 处理业务逻辑
    if (result.code !== 200) {
      throw new Error(result.message || '获取数据失败');
    }

    console.log('分析数据:', result.data);
    return result.data;

  } catch (error) {
    console.error('请求出错:', error.message);
    // 可在此添加UI错误提示
    return null;
  }}




// 📌 更新分数的函数
function updateScore(id, score) {
    let element = document.getElementById(id);
    if (element) {
        element.textContent = score || "--";
        element.classList.remove("animate-pulse"); // 移除加载动画
    }
}
let radarChart = null;

/**
 * 初始化雷达图（适配图片中的样式）
 */
function initRadarChart() {
    const chartDom = document.getElementById('scoreChart');
    if (!chartDom) return;

    // 初始化图表实例
    radarChart = echarts.init(chartDom);

    // 默认配置（保持与图片一致的风格）
    const defaultOption = {
        title: {
            text: "评分维度分析",
            left: "center",
            textStyle: {
                fontSize: 18,
                fontWeight: "bold",
                color: "#333"
            }
        },
        tooltip: {
            trigger: "item",
            formatter: params => {
                return `${params.name}<br/>得分: ${params.value}`;
            }
        },
        radar: {
            shape: 'circle',
            indicator: [
                { name: "词评分", max: 25, color: '#1890FF' },
                { name: "句子评分", max: 25, color: '#722ED1' },
                { name: "结构评分", max: 25, color: '#13C2C2' },
                { name: "内容评分", max: 25, color: '#F759AB' }
            ],
            radius: "65%",
            axisName: {
                color: "#666",
                fontSize: 12,
                fontWeight: "bold"
            },
            splitLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.1)",
                    width: 1
                }
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ["rgba(25, 180, 120, 0.1)", "rgba(25, 180, 120, 0.05)"]
                }
            },
            axisLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.3)",
                    width: 1
                }
            }
        },
        series: [{
            type: "radar",
            lineStyle: {
                width: 2,
                color: "rgba(54, 162, 235, 0.8)"
            },
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
                color: "#fff",
                borderColor: "rgba(54, 162, 235, 1)",
                borderWidth: 2
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(58, 77, 233, 0.5)' },
                    { offset: 1, color: 'rgba(0, 195, 255, 0.2)' }
                ])
            },
            data: [{
                value: [18, 16, 20, 15], // 初始零值
                name: "上次数据"
            }]
        }]
    };

    radarChart.setOption(defaultOption);

    // 响应式调整
    window.addEventListener('resize', function() {
        radarChart && radarChart.resize();
    });
    // 在initRadarChart中添加容器检查
const chartDom1 = document.getElementById('scoreChart');
if (!chartDom1) {
  console.error('错误: 找不到DOM容器 #scoreChart');
  // 创建备用容器（应急方案）
  const fallbackContainer = document.createElement('div');
  fallbackContainer.id = 'scoreChart';
  document.body.appendChild(fallbackContainer);
};
}

/**
 * 更新雷达图数据（增强错误处理）
 */
async function updateRadarChart(essayId, versionId,feedbackLanguage) {
    if (!radarChart) initRadarChart();

    try {
        // 显示加载状态
        radarChart.showLoading();


        // 获取数据
        const response = await fetch('http://127.0.0.1:5004/visualization/radar', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ essay_id: essayId, version_id: versionId })
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const result = await response.json();
        console.log('接口返回数据:', JSON.stringify(result));
        console.log('接口返回数据:', JSON.stringify(result.data));
        if (result.code !== 200) throw new Error(result.message || 'Invalid data');

        // 验证数据格式
        const validateScores = (scores) => {
            if (!Array.isArray(scores) || scores.length !== 4) {
                throw new Error('数据格式错误：需要4个评分维度');
            }
            return scores.map(v => Math.min(Math.max(v, 0), 25)); // 限制在0-25范围
        };

        const scores = validateScores(result.data.values || []);
        console.log(scores);
        // 在setOption之前添加
console.log('最终渲染数据:', {
    scores: scores,
    dimensions: ["词评分","句子评分","结构评分","内容评分"],
    containerSize: document.getElementById('scoreChart').getBoundingClientRect()
});
// 完整图表配置（匹配图片样式）
        radarChart.setOption({
        title: {
            text: "评分维度分析",
            left: "center",
            textStyle: {
                fontSize: 18,
                fontWeight: "bold",
                color: "#333"
            }
        },
         tooltip: {
            trigger: "item",
            formatter: params => {
                return `${params.name}<br/>得分: ${params.value}`;
            }
        },
            radar: {
                indicator: [
                    { name: "词评分", max: 25, color: '#1890FF' },
                    { name: "句子评分", max: 25, color: '#722ED1' },
                    { name: "结构评分", max: 25, color: '#13C2C2' },
                    { name: "内容评分", max: 25, color: '#F759AB' }
                ],
                 axisLabel: {
            show: true,
            formatter: (name, index) => {
                return `${name}: ${scores[index]}`; // 显示"维度: 分数"
            },
            color: '#333'}

    },
    radar: {
            shape: 'circle',
            indicator: [
                { name: "词评分", max: 25, color: '#1890FF' },
                { name: "句子评分", max: 25, color: '#722ED1' },
                { name: "结构评分", max: 25, color: '#13C2C2' },
                { name: "内容评分", max: 25, color: '#F759AB' }
            ],
            radius: "65%",
            axisName: {
                color: "#666",
                fontSize: 12,
                fontWeight: "bold"
            },
            splitLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.1)",
                    width: 1
                }
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ["rgba(25, 180, 120, 0.1)", "rgba(25, 180, 120, 0.05)"]
                }
            },
            axisLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.3)",
                    width: 1
                }
            }
        },
        series: [{
            type: "radar",
            lineStyle: {
                width: 2,
                color: "rgba(54, 162, 235, 0.8)"
            },
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
                color: "#fff",
                borderColor: "rgba(54, 162, 235, 1)",
                borderWidth: 2
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(58, 77, 233, 0.5)' },
                    { offset: 1, color: 'rgba(0, 195, 255, 0.2)' }
                ])
            },
            data: [{
                value: scores, // 初始零值
                name: "本次评分数据"
            }]
        }]

        }, true);

    } catch (error) {
        console.error('雷达图更新失败:', error);

        // 错误状态显示（红色警示）
        radarChart.setOption({
            series: [{
                data: [{
                    value: [0, 0, 0, 0],
                    name: '加载失败',
                    itemStyle: { color: '#ff4d4f' }
                }]
            }],
            title: {
                subtext: error.message,
                subtextStyle: {
                    color: '#f56c6c',
                    fontWeight: 'bold'
                }
            }
        }, true);

//        // 3秒后自动重试
//        setTimeout(() => updateRadarChart(essayId, versionId), 3000);
    } finally {
        radarChart.hideLoading();
    }
};


// 页面加载初始化
document.addEventListener('DOMContentLoaded', initRadarChart);

// 通用下拉菜单控制函数
function toggleDropdown(dropdownId) {
  const dropdown = document.getElementById(dropdownId);
  const isOpening = dropdown.style.display !== 'block';

  // 关闭所有其他下拉菜单
  document.querySelectorAll('.dropdown').forEach(d => {
    if (d.id !== dropdownId) {
      d.style.display = 'none';
      // 重置其他下拉菜单的箭头
      const otherChevron = d.previousElementSibling?.querySelector('.fa-chevron-down');
      otherChevron?.classList.remove('rotate-180');
    }
  });

  // 切换当前下拉菜单状态
  dropdown.style.display = isOpening ? 'block' : 'none';

  // 切换箭头方向（如果存在）
  const chevron = dropdown.previousElementSibling?.querySelector('.fa-chevron-down');
  if (chevron) {
    chevron.classList.toggle('rotate-180', isOpening);
  }
}

// 通用选择函数
function selectOption(optionType, value, displayElementId, dropdownId) {
  // 更新显示的选中项
  document.getElementById(displayElementId).textContent = value;
  // 隐藏下拉菜单
  document.getElementById(dropdownId).style.display = 'none';
  // 重置箭头方向
  const chevron = document.getElementById(dropdownId).previousElementSibling?.querySelector('.fa-chevron-down');
  chevron?.classList.remove('rotate-180');

  // 根据选择类型执行不同逻辑
  switch(optionType) {
    case 'type':
      console.log('已选择作文类型:', value);
      // 处理作文类型变化的逻辑
      break;
    case 'model':
      console.log('已选择评分模型:', value);
      // 处理评分模型变化的逻辑
      break;
  }
}

// 点击页面其他位置关闭所有下拉菜单
document.addEventListener('click', function(event) {
  const dropdowns = document.querySelectorAll('.dropdown');
  const dropdownButtons = document.querySelectorAll('[onclick^="toggleDropdown"]');

  // 如果点击的不是下拉按钮或下拉菜单内容
  const isClickInside = Array.from(dropdowns).some(dropdown => dropdown.contains(event.target)) ||
                       Array.from(dropdownButtons).some(button => button.contains(event.target));

  if (!isClickInside) {
    dropdowns.forEach(dropdown => {
      dropdown.style.display = 'none';
      const chevron = dropdown.previousElementSibling?.querySelector('.fa-chevron-down');
      chevron?.classList.remove('rotate-180');
    });
  }
});

// 初始化隐藏所有下拉菜单
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.dropdown').forEach(dropdown => {
    dropdown.style.display = 'none';
  });
});


//更新评分详情
function updateScoreDisplay(data) {

console.log(data);
  // 其他细节（你可以更新为表格或标签显示）
  document.getElementById("total_Score").textContent = data.overall_score;
  document.getElementById("vocabulary_Score").textContent = data.vocabulary_score.total;
  document.getElementById("sentence_Score").textContent = data.sentence_score.total;
  document.getElementById("structure_Score").textContent = data.structure_score.total;
  document.getElementById("content_Score").textContent = data.content_score.total;
 // 显示评分结果区域
    const scoreContainer = document.getElementById('scoreContainer1');
    if (scoreContainer) {
        scoreContainer.style.display = 'grid';
    }

// 更新优秀句子
const sentencesContainer = document.querySelector('.good-sentences .sentence-list');
  // 清空容器确保只显示最新内容
    if (sentencesContainer) {
        sentencesContainer.innerHTML = '';

        if (Array.isArray(data.excellent_expressions) && data.excellent_expressions.length > 0) {
            data.excellent_expressions.forEach(sentence => {
                const sentenceItem = document.createElement('li');
                sentenceItem.className = 'sentence-item';

                // 原文引用部分
                const quoteBlock = document.createElement('div');
                quoteBlock.className = 'sentence-quote';
                quoteBlock.innerHTML = `
                    <i class="fas fa-quote-left text-green-500 opacity-50 mr-1"></i>
                    ${sentence.quote}
                `;

                // 原因说明部分
                const reasonBlock = document.createElement('div');
                reasonBlock.className = 'sentence-reason';
                reasonBlock.innerHTML = `
                    <span class="font-medium text-green-600">分析: ${sentence.reason}</span>
                `;

                // 组装元素
                sentenceItem.appendChild(quoteBlock);
                sentenceItem.appendChild(reasonBlock);
                sentencesContainer.appendChild(sentenceItem);
            });
        } else {
            const emptyMessage = document.createElement('li');
            emptyMessage.className = 'no-sentence';
            emptyMessage.textContent = '暂无优秀句子标记';
            sentencesContainer.appendChild(emptyMessage);
        }
    }

/**
 * 显示评分进度条
 * @param {string} message - 初始状态消息
 */
function showScoringProgress(message = "正在分析作文内容") {
    const progressElement = document.getElementById('scoring-progress');
    const statusElement = document.getElementById('scoring-status');

    // 更新状态消息
    statusElement.textContent = message;

    // 显示进度条
    progressElement.classList.remove('hidden');

    // 模拟进度更新（实际使用时可以根据API调用阶段更新）
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 10;
        if (progress > 90) clearInterval(progressInterval);
        updateProgressBar(Math.min(progress, 90));
    }, 800);

    return {
        update: (newMessage, newProgress) => {
            statusElement.textContent = newMessage;
            if (typeof newProgress !== 'undefined') {
                updateProgressBar(newProgress);
            }
        },
        complete: () => {
            clearInterval(progressInterval);
            updateProgressBar(100);
            setTimeout(() => {
                progressElement.classList.add('hidden');
            }, 1000);
        },
        error: (errorMessage) => {
            clearInterval(progressInterval);
            statusElement.textContent = errorMessage;
            document.getElementById('scoring-progress-bar').classList.remove('bg-blue-600');
            document.getElementById('scoring-progress-bar').classList.add('bg-red-500');
            setTimeout(() => {
                progressElement.classList.add('hidden');
                // 重置样式
                document.getElementById('scoring-progress-bar').classList.remove('bg-red-500');
                document.getElementById('scoring-progress-bar').classList.add('bg-blue-600');
            }, 3000);
        }
    };
}


//const sentencesContainer = document.querySelector('.good-sentences .sentence-list');
//console.log(data.excellent_expressions);
//if (sentencesContainer) {
//    if (Array.isArray(data.excellent_expressions) && data.excellent_expressions.length > 0) {
//        sentencesContainer.innerHTML = data.excellent_expressions
//          .map(sentence => `<li class="flex items-start">
//                <span class="text-green-500 mr-2 mt-1">•</span>
//                <span class="sentence-quote">${sentence.quote}</span>
//
//                <span class="ml-2 text-gray-600"></span><span class="sentence-reason">${sentence.reason}</span><span class="text-gray-600"></span>
//            </li>`)
//          .join('');
//    } else {
//        sentencesContainer.innerHTML = '<li class="text-gray-500">暂无优秀句子标记</li>';
//    }
//}
    // 更新写作建议
    const suggestionsContainer = document.querySelector('.suggestions .suggestion-list');
    if (suggestionsContainer) {
        if (Array.isArray(data.suggestions) && data.suggestions.length > 0) {
            suggestionsContainer.innerHTML = data.suggestions
                .map(suggestion => `<li class="flex items-start">
                    <span class="text-blue-500 mr-2 mt-1">•</span>
                    <span>${suggestion}</span>
                </li>`)
                .join('');
        } else {
            suggestionsContainer.innerHTML = '<li class="text-gray-500">暂无写作建议</li>';
        }
    }

}

// 添加点击处理函数
document.addEventListener('DOMContentLoaded', function() {
    // 处理好词点击
    document.querySelectorAll('.bg-yellow-50 .px-2').forEach(word => {
        word.addEventListener('click', function() {
            showDetailPopup('word', this.textContent.trim());
        });
    });

    // 处理好句点击
    document.querySelectorAll('.bg-blue-50 .p-2').forEach(sentence => {
        sentence.addEventListener('click', function() {
            showDetailPopup('sentence', this.querySelector('p').textContent);
        });
    });

    // 处理好段落点击
    document.querySelectorAll('.bg-purple-50 .p-2').forEach(paragraph => {
        paragraph.addEventListener('click', function() {
            showDetailPopup('paragraph', this.querySelector('p').textContent);
        });
    });
});

// 显示详细信息弹窗
function showDetailPopup(type, content) {
    const popup = document.createElement('div');
    popup.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';

    let title, analysis;
    switch(type) {
        case 'word':
            title = '词语赏析';
            analysis = getWordAnalysis(content);
            break;
        case 'sentence':
            title = '句子赏析';
            analysis = getSentenceAnalysis(content);
            break;
        case 'paragraph':
            title = '段落赏析';
            analysis = getParagraphAnalysis(content);
            break;
    }

    popup.innerHTML = `
        <div class="bg-white rounded-lg p-6 max-w-2xl mx-4 relative">
            <button class="absolute right-4 top-4 text-gray-500 hover:text-gray-700" onclick="this.closest('.fixed').remove()">
                <i class="fas fa-times"></i>
            </button>
            <h3 class="text-xl font-medium mb-4">${title}</h3>
            <div class="mb-4 p-3 bg-gray-50 rounded">
                <p class="text-gray-700">${content}</p>
            </div>
            <div class="space-y-3">
                ${analysis}
            </div>
            <div class="mt-6 text-right">
                <button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onclick="this.closest('.fixed').remove()">
                    关闭
                </button>
            </div>
        </div>
    `;

    document.body.appendChild(popup);
};

// 获取词语分析
function getWordAnalysis(word) {
    return `
        <div class="space-y-2">
            <p><strong>释义：</strong><span class="text-gray-700">...</span></p>
            <p><strong>用法示例：</strong><span class="text-gray-700">...</span></p>
            <p><strong>同义词：</strong><span class="text-gray-700">...</span></p>
            <p><strong>使用建议：</strong><span class="text-gray-700">...</span></p>
        </div>
    `;
}

// 获取句子分析
function getSentenceAnalysis(sentence) {
    return `
        <div class="space-y-2">
            <p><strong>修辞手法：</strong><span class="text-gray-700">...</span></p>
            <p><strong>句式分析：</strong><span class="text-gray-700">...</span></p>
            <p><strong>写作技巧：</strong><span class="text-gray-700">...</span></p>
            <p><strong>改写建议：</strong><span class="text-gray-700">...</span></p>
        </div>
    `;
};

// 获取段落分析
function getParagraphAnalysis(paragraph) {
    return `
        <div class="space-y-2">
            <p><strong>段落主旨：</strong><span class="text-gray-700">...</span></p>
            <p><strong>写作特色：</strong><span class="text-gray-700">...</span></p>
            <p><strong>结构分析：</strong><span class="text-gray-700">...</span></p>
            <p><strong>改进建议：</strong><span class="text-gray-700">...</span></p>
        </div>
    `;
};


// 显示/隐藏加载状态
function showLoading(show) {
    const loadingEl = document.getElementById('loading');
    if (show) {
        loadingEl.classList.remove('hidden');
    } else {
        loadingEl.classList.add('hidden');
    }
};
/**
 * 更新进度条
 * @param {number} percentage - 进度百分比(0-100)
 */
function updateProgressBar(percentage) {
    const progressBar = document.getElementById('scoring-progress-bar');
    progressBar.style.width = `${percentage}%`;
};
/**
 * 显示评分进度条
 * @param {string} message - 初始状态消息
 */
function showScoringProgress(message = "正在分析作文内容") {
    const progressElement = document.getElementById('scoring-progress');
    const statusElement = document.getElementById('scoring-status');

    // 更新状态消息
    statusElement.textContent = message;

    // 显示进度条
    progressElement.classList.remove('hidden');

    // 模拟进度更新（实际使用时可以根据API调用阶段更新）
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 10;
        if (progress > 90) clearInterval(progressInterval);
        updateProgressBar(Math.min(progress, 90));
    }, 800);

    return {
        update: (newMessage, newProgress) => {
            statusElement.textContent = newMessage;
            if (typeof newProgress !== 'undefined') {
                updateProgressBar(newProgress);
            }
        },
        complete: () => {
            clearInterval(progressInterval);
            updateProgressBar(100);
            setTimeout(() => {
                progressElement.classList.add('hidden');
            }, 1000);
        },
        error: (errorMessage) => {
            clearInterval(progressInterval);
            statusElement.textContent = errorMessage;
            document.getElementById('scoring-progress-bar').classList.remove('bg-blue-600');
            document.getElementById('scoring-progress-bar').classList.add('bg-red-500');
            setTimeout(() => {
                progressElement.classList.add('hidden');
                // 重置样式
                document.getElementById('scoring-progress-bar').classList.remove('bg-red-500');
                document.getElementById('scoring-progress-bar').classList.add('bg-blue-600');
            }, 3000);
        }
    };
}